<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formItem } from '../form-item'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import { TableItem } from '@/api/common'
import gdyjService from '@/api/gdyj'
import xtpzService from '@/api/xtpz'
import TreeUtilDTO from '@/utils/tree'
import router from '@/router/index'
import gddjbDialog from '@/components/queryTable/table/dialogs/gddjb-dialog.vue'
import fqjdDialog from '../dialogs/fqjd-dialog.vue'
import { useMainStore } from '@/store/main'
const emit = defineEmits(['refresh', 'addTgjlTab'])
const store = useMainStore()
const formLabel = ref()
const loading = ref()
// 控制更多条件显示隐藏
const moreShow = ref(true)

// 生命周期
onMounted(async () => {
  // 查询列表数据
  loading.value = true
  formLabel.value = await formItem('gdyjCqyj')
  await init()
  loading.value = false
})

const init = async () => {
  // 获取案件类别
  getAjlb()
  // 获取权限数据
  queryDlrsjqx()
}

// 更多条件查询
const form = ref<any>({
  pageSize: 20,
  pageNum: 1,
  filter: {
    ajlbbm: [],
    ajlxbm: '',
    ajmc: '',
    bjjsrq: undefined,
    bjksrq: undefined,
    bmsah: '',
    cbbmbm: '',
    cbbmbmList: [],
    cbdwbmList: [],
    dh: '',
    gdjsrq: undefined,
    gdksrq: undefined,
    gdr: '',
    gdztbm: '',
    jcg: '',
    shztbm: '',
    tgztdm: '',
    tjjsrq: undefined,
    tjksrq: undefined,
    tysah: '',
    yjztbm: '',
  },
})

// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '案件名称',
      prop: 'ajmc',
      width: 200,
      custom: true,
      sort: true,
      dqfs: 'left',
    },
    { label: '部门受案号', prop: 'bmsah', width: 300, dqfs: 'left' },
    { label: '统一受案号', prop: 'tysah', width: 200, dqfs: 'left' },
    { label: '案件类别', prop: 'ajlbmc', width: 200, dqfs: 'left' },
    { label: '承办部门', prop: 'cbbmmc', width: 150, dqfs: 'left' },
    { label: '检察官', prop: 'cbjcg', width: 130, dqfs: 'left' },
    { label: '案卷类别', prop: 'ajlxmc', width: 120, dqfs: 'left' },
    { label: '归档人', prop: 'gdrxm', width: 120, dqfs: 'left' },
    { label: '提交日期', prop: 'tjrq', width: 130, dqfs: 'left' },
    {
      label: '审核状态',
      prop: 'shztmc',
      width: 120,
      dqfs: 'left',
    },
    { label: '归档状态', prop: 'gdztmc', width: 120, dqfs: 'left', gdzt: true },
    { label: '归档日期', prop: 'gdtgrq', width: 130, dqfs: 'left' },
    { label: '档号', prop: 'dh', width: 130, dqfs: 'left' },
    { label: '剩余期限', prop: 'syqx', width: 120, dqfs: 'left' },
    { label: '办结日期', prop: 'bjrq', width: 130, dqfs: 'left' },
    { label: '退改次数', prop: 'tgcs', width: 130, dqfs: 'left' },
    { label: '退改状态', prop: 'tgztmc', width: 120, dqfs: 'left' },
  ],
})

const total = ref<number>(0)
const page = computed(() => {
  return {
    pageNum: form.value.pageNum,
    pageSize: form.value.pageSize,
    total: total.value,
    exportParams: {
      url: `${window.IPCONFIG}/api/gdyj/queryCqyjlb`,
      wjmc: '超期预警',
    },
  }
})

// 页码发生改变时
const changePageNum = (val: number) => {
  form.value.pageNum = val
  queryTable()
  getGdl()
}

// 页条数发生改变时
const changeSize = (val: number) => {
  form.value.pageNum = 1
  form.value.pageSize = val
  queryTable()
  getGdl()
}

/*
 * 查询列表数据
 */
const queryTable = (refresh?: boolean) => {
  const params = { ...form.value }
  if (!params.filter.cbdwbmList || params.filter.cbdwbmList.length === 0) {
    ElMessage({ type: 'warning', message: '请选择承办单位' })
    return
  }
  if (!params.filter.cbbmbmList) {
    params.filter.cbbmbmList = []
  }
  loading.value = true
  gdyjService
    .queryCqyjlb(params)
    .then((res) => {
      tableData.value.data = res.data.list
      total.value = res.data.total
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

// 子组件传过来的方法
const searchTable = (data: any) => {
  if (!data.cbdwbmList || data.cbdwbmList?.length === 0) {
    ElMessage({ type: 'warning', message: '请选择承办单位' })
    return
  }
  let newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      const kssj = key.replace('-rq', 'ksrq')
      const jssj = key.replace('-rq', 'jsrq')
      if (data[key]?.length) {
        newObj[kssj] = data[key][0]
        newObj[jssj] = data[key][1]
      } else {
        newObj[kssj] = ''
        newObj[jssj] = ''
      }
    }
    newObj[key] = data[key]
  }
  form.value.filter = newObj
  queryTable()
  getGdl()
}

/*
 * 查询归档率
 */
// 归档率
const GdlGetOutputDTO = ref({
  gdl: '', // 归档率
  cqgdl: '', // 超期归档率
})

const getGdl = () => {
  const params = form.value.filter
  gdyjService
    .getGdl(params)
    .then((res) => {
      GdlGetOutputDTO.value.gdl = res.data.gdl.replace('%', '')
      GdlGetOutputDTO.value.cqgdl = res.data.cqgdl.replace('%', '')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/**
 * 表格选择
 */
const multipleSelection = ref<any[]>([])
const selectionChange = (val: any[]) => {
  multipleSelection.value = val
}

/*
 * 点击案件名称进入归档
 */
const checkRow = (row: any) => {
  router.push({
    path: '/jcgshxq',
    query: {
      ...row,
      route: '/gdyj',
      jumpFrom: '',
    },
  })
}

const tableBoxRef = ref<InstanceType<typeof tableBox>>()

const rowClick = (row: any) => {
  if (multipleSelection.value?.includes(row)) {
    tableBoxRef.value?.refTable.toggleRowSelection(row, false)
  } else {
    tableBoxRef.value?.refTable.toggleRowSelection(row, true)
  }
}

/*
 * 打开归档跟踪弹窗
 */
const openGdgz = (row: any) => {
  tableBoxRef.value?.openGdgzDialog(row.gdbh)
}

/*
 * 打开归档登记表弹窗
 */
const gddjbDialogRef = ref<InstanceType<typeof gddjbDialog>>()
const openGddjb = (arr: any) => {
  const gdbhList = arr.map((el: any) => el.gdbh)
  gddjbDialogRef.value!.openDialog(gdbhList, '归档登记表')
}

/*
 * 打开继续监督弹窗
 */
const fqjdDialogRef = ref<InstanceType<typeof fqjdDialog>>()
const openFqjd = () => {
  fqjdDialogRef.value!.openDialog(multipleSelection.value[0])
}

const refresh = () => {
  if (!form.value.filter.cbdwbmList || form.value.filter.cbdwbmList.length === 0) {
    ElMessage({ type: 'warning', message: '请选择承办单位' })
    return
  }
  queryTable(true)
}

const optionsObj = ref<any>({
  ajlbbm: [],
  cbbmbmList: [],
  cbdwbmList: [],
})

/*
 * 获取案件类别
 */
const getAjlb = async () => {
  await xtpzService
    .queryAjlblb()
    .then((res) => {
      if (res) {
        optionsObj.value.ajlbbm = TreeUtilDTO.getTreeData(res.data || [], 'dm', 'fdm')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 获取部门列表
 */
const queryDataObj = ref({
  cbdwbmList: [] as any[],
  cbbmbmList: [] as any[],
})
const queryDlrsjqx = () => {
  xtpzService.getDlrsjqx({}).then((res: any) => {
    optionsObj.value.cbdwbmList = TreeUtilDTO.getTreeData(
      (res.data.sqdwxxList || []).map((el: any) => ({
        ...el,
        mc: el.dwmc,
        dm: el.dwbm,
        fdm: el.fdwbm,
      })),
      'dwbm',
      'fdwbm',
    )
    if (optionsObj.value.cbdwbmList.length > 0) {
      form.value.filter.cbdwbmList.push(optionsObj.value.cbdwbmList[0]?.dm)
      queryDataObj.value.cbdwbmList.push(optionsObj.value.cbdwbmList[0]?.dm)
    } else {
      form.value.filter.cbdwbmList = [store.userInfo.dwbm]
      queryDataObj.value.cbdwbmList = [store.userInfo.dwbm]
    }
    optionsObj.value.cbbmbmList = (optionsObj.value.cbdwbmList[0]?.sqbmxxList || []).map(
      (el: any) => {
        return {
          dm: el.bmbm,
          mc: el.bmmc,
        }
      },
    )
    form.value.filter.cbbmbmList = optionsObj.value.cbbmbmList.map((bm: any) => bm.dm)
    queryDataObj.value.cbbmbmList = optionsObj.value.cbbmbmList.map((bm: any) => bm.dm)
    changePageNum(1)
  })
}

watch(
  () => form.value.filter.cbdwbmList,
  () => {
    if (form.value.filter.cbdwbmList?.length === 1) {
      const dw = TreeUtilDTO.findNode(
        optionsObj.value.cbdwbmList,
        form.value.filter.cbdwbmList[0],
        'dwbm',
      )
      optionsObj.value.cbbmbmList =
        dw?.sqbmxxList?.map((el: any) => {
          return {
            dm: el.bmbm,
            mc: el.bmmc,
          }
        }) || []
    } else {
      form.value.filter.cbbmbmList = undefined
      optionsObj.value.cbbmbmList = []
    }
  },
  {
    deep: true,
  },
)

/*
 * 打开退改记录tab
 */
const openTgjl = (data: any) => {
  emit('addTgjlTab', data)
}
</script>
<template>
  <div class="container">
    <div class="progress-box">
      <div class="progress">
        <div class="progress-left">
          <span>归档率:</span>
          <el-progress
            :text-inside="false"
            :stroke-width="20"
            color="#4ad662"
            :percentage="GdlGetOutputDTO.gdl"
          />
        </div>
        <div class="progress-right">
          <span>超期归档率:</span>
          <el-progress
            :text-inside="false"
            :stroke-width="20"
            color="#f46961"
            :percentage="GdlGetOutputDTO.cqgdl"
          />
        </div>
      </div>
    </div>
    <div class="form">
      <form-box
        :formData="form.filter"
        :formLabel="formLabel"
        :moreShow="moreShow"
        :optionsObj="optionsObj"
        :queryDataObj="queryDataObj"
        @searchEvent="searchTable"
      ></form-box>
    </div>

    <div class="submit-list">
      <div>
        <button class="btn_operation" :disabled="multipleSelection.length !== 1" @click="openFqjd">
          <div class="btn-shtg"></div>
          发起监督
        </button>
        <button class="btn_operation" @click="refresh">
          <div class="btn-refresh"></div>
          刷新
        </button>
      </div>
    </div>

    <div class="table">
      <table-box
        gnbm="cqyj"
        ref="tableBoxRef"
        :tableData="tableData"
        :selectShow="true"
        :showExport="true"
        :getTableDataParam="page"
        :formParams="
          form.filter.cbbmbmList ? form : { ...form, filter: { ...form.filter, cbbmbmList: [] } }
        "
        @selectionChange="selectionChange"
        @changeCurrent="changePageNum"
        @changeSize="changeSize"
        @checkRow="checkRow"
        @rowClick="rowClick"
      >
        <template #myAction>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <div class="active-img" title="归档跟踪" @click="openGdgz(scope.row)">
                <img src="@/assets/images/gdgztext.png" />
              </div>
              <div
                class="active-img"
                title="归档登记表"
                @click="openGddjb([scope.row])"
                v-if="scope.row.gdztmc !== '未归档' || scope.row.tjrq"
              >
                <img src="@/assets/images/gddjb.png" />
              </div>
              <div
                class="active-img"
                title="退改记录"
                @click="openTgjl(scope.row)"
                v-if="scope.row.tgcs"
              >
                <img src="@/assets/images/tgjl.png" />
              </div>
            </template>
          </el-table-column>
        </template>
      </table-box>
    </div>
    <!--归档登记表-->
    <gddjb-dialog ref="gddjbDialogRef" />
    <!--发起监督-->
    <fqjd-dialog ref="fqjdDialogRef" @refresh="queryTable" />
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .progress-box {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #dae4f1;
    margin-bottom: 26px;
    .progress {
      width: 80%;
      padding: 10px 0 20px 0;
      display: flex;
      .progress-left {
        display: flex;
        flex: 1;
        & > span {
          display: inline-block;
          width: 60px;
        }
        .el-progress {
          width: 100%;
        }
      }

      .progress-right {
        display: flex;
        flex: 1;
        padding-left: 20px;
        & > span {
          display: inline-block;
          width: 90px;
        }
        .el-progress {
          width: 100%;
        }
      }
    }
  }

  .submit-list {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .table {
    flex: 1;
    flex-shrink: 0;
    overflow: auto;
  }

  .active-img {
    float: left;
    cursor: pointer;
  }
  .active-img + .active-img {
    margin-left: 10px;
  }
}
</style>
